package com.wzgl.core.server;

import java.util.Date;
import java.util.Map;
import java.util.Random;

import com.jfinal.aop.Before;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.wzgl.core.CacheConsts;
import com.wzgl.core.model.RecordBaseDao;
import com.wzgl.core.model.Tdirection;
import com.wzgl.core.model.Tgrid;
import com.wzgl.core.model.TgridResult;
import com.wzgl.core.model.Tusers;
import com.wzgl.core.utils.UuidUtil;
import com.wzgl.core.utils.WZGLUtils;
import com.wzgl.core.webmagic.utils.PinyinUtils;
import com.wzgl.core.xny.model.TnewextendsXny;
import com.wzgl.core.xny.model.TnewsXny;

import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class GirdService {
	/***
	 * 发布格子
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public boolean operGird(Map<String, String[]> map) throws Exception{
		boolean b = false;
		b = RecordBaseDao.saveObject(map,"tgrid");
		return b;
	}
	
	public boolean saveImg(Map<String, String> map) throws Exception{
		boolean b = false;
		b = RecordBaseDao.insertObject(map,"tgrid_img");
		return b;
	}
	
	public boolean delImg(Map<String, String> map) throws Exception{
		boolean b = false;
		b = RecordBaseDao.editObject(map, "tgrid_img");
		return b;
	}
	/***
	 * 保存爬虫文章数据
	 * @param t
	 * @return
	 * @throws Exception
	 */
	public boolean saveMagicTgrids(Tgrid t)throws Exception{
		boolean b = false;
		try {
			if(StrKit.isBlank(t.getFid())){
				t.setFid(UuidUtil.get32UUID());
				b = t.save();
			}else{
				b = t.update();
			}
		} catch (Exception e) {
			b = false;
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return b;
	}
	@Before(Tx.class)
	public Ret canleGrid(final Tgrid t)throws Exception{
		 t.setFstatus(0);
		 if(!t.update()){
			 return Ret.fail("msg", "取消审核失败,请稍后再试!");
		 }
		 TgridResult tr = TgridResult.dao.findById(t.getFid());
		 tr.setFstatus(-1);
		 if(!tr.update()){
			 return Ret.fail("msg", "取消审核失败,请稍后再试!");
		 }
		 return Ret.ok("msg","取消审核成功！");
	}
	@Before(Tx.class)
	public Ret saveGrid(final Tgrid t,final Tusers user)throws Exception{
		if(StrKit.isBlank(t.getFid())){
			t.setFid(UuidUtil.get32UUID());
			if(!t.save()){
				return Ret.fail("msg", "文章保存失败,请稍后再试!");
			}
		  }else{
			  if(t.getFstatus() == 1){
				  //审核文章
	              Tgrid tgrid = Tgrid.dao.findById(t.getFid());
				  if(tgrid.getFstatus() == 1){
				    return Ret.fail("msg", "当前文章已经审核,请刷新数据!");
				  }
				  
				  TgridResult tr = TgridResult.dao.findById(tgrid.getFid());
				  if(tr != null){
					 tr.setFstatus(0);
					 if(!tr.update()){
						 return Ret.fail("msg", "文章审核失败,请稍后再试!");
					 }
				  }else{
					  Record r = tgrid.toRecord();
					  r.set("fuserId", user.getFid());
					  r.set("fdate", new Date());
					  if(!Db.save("tgrid_result", r)){
						  return Ret.fail("msg", "文章审核失败,请稍后再试!");
					  }
				  }
			  }
			  if(!t.update()){
		  		return Ret.fail("msg", "文章更新失败,请稍后再试!");
			  }
		  }
		 return Ret.ok("msg","保存成功！");
	}
	
	//保存Tnews
	@Before(Tx.class)
	public Ret saveTnews(TnewsXny news, TgridResult tgrid, Tdirection tdirect) throws BadHanyuPinyinOutputFormatCombination{	
		news.setTitle(tgrid.getFtitle());
		news.setAuthor("转载自"+tgrid.getFfrom());
		//news.setCopyFrom(tgrid.getFfrom());
		news.setDateTime(new Date());
		news.setDeviceP(true);
		news.setDeviceM(false);
		news.setDeviceApp(false);
		news.setDeviceW(false);
		news.setClickCount(getRandom(50, 200));//50-200随机数
		news.setIsHot(false);
		news.setIsAllowComments(false);
		news.setWaterMarkConfig("");
		news.setUserId(0);
		news.setToUserId(0);
		news.setParentId(0);
		news.setHtmlSaveDirectory("");
		news.setHtmlFileName(PinyinUtils.getPinYinHeadChar(tgrid.getFtitle().substring(0,2)));//标题首字母
		news.setUpdateHTML(false);
		news.setLastDevStatus("1000");
		news.setIsAudited(false);
		news.setReleVirtualType(0);
		news.setUserGroupID(0);
		
		Ret ret = new Ret();
		if(news.save()){	
			ret.set("newsId", news.getId());
			return ret.setOk();
		}else{
			return ret.setFail();
		}
	}
	
	//保存Tnewextends
	@Before(Tx.class)
	public Ret saveTnewExtends(TnewextendsXny ext, TgridResult tgrid, TnewsXny news, Tdirection tdirect) throws BadHanyuPinyinOutputFormatCombination{
		//**通过去向再分开调用相应逻辑
		
		ext.setMasterId(Integer.valueOf(news.getId()));
		ext.setContent(tgrid.getFhtml());
		ext.setImageUrl(tgrid.getFcoverImg());
		ext.setKeywords(PinyinUtils.getPinYinHeadChar(tgrid.getFtitle().substring(0,2)));//标题首字母
		ext.setSmallImageUrl(tgrid.getFcoverImg());
		ext.setBigImageUrl(tgrid.getFcoverImg2());
		ext.setIsPush(false);
		ext.setDataVersion((new Date()).getTime());
		ext.setIshead(true);
		ext.setIsHome(true);
		ext.setIsNew(true);
		ext.setDeviceType(1);
		try {
			Thread.sleep(5);
			if(!"".equals(tgrid.getFtype()) && tgrid.getFtype().equals("100008")){
				ext.setTypeId(4);   //默认大型单机
			}else if(!"".equals(tgrid.getFtype()) && tgrid.getFtype().equals("100009")){
				ext.setTypeId(29);  //默认大型单机
			}else if(!"".equals(tgrid.getFtype()) && tgrid.getFtype().equals("100010")){
				ext.setTypeId(142);  //默认图片
			}else if(!"".equals(tgrid.getFtype()) && tgrid.getFtype().equals("100011")){
				ext.setTypeId(144);  //默认杂谈
			}else{
				ext.setTypeId(144);  //默认杂谈
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
			throw new RuntimeException("暂停失败...");
		}
		
		ext.setOrder(1);
		ext.setIsShow(false);
		ext.setContentType(4);
		
		Ret ret = new Ret();
		if(ext.save()){
			ret.set("newsExtendsId", ext.getId());
			return ret.setOk();
		}else{
			return ret.setFail();
		}
	}
	
	public static String getRandom(int min,int max){
		Random random = new Random();
		return (random.nextInt(max)%(max-min+1) + min)+"";
	}
	
	
	public boolean saveMagicTgridsImg(Tgrid t) {
		boolean b = false;
		try {
			if(StrKit.isBlank(t.getFid())){
				t.setFid(UuidUtil.get32UUID());
				b = t.save();
			}else{
				b = t.update();
			}
		} catch (Exception e) {
			b = false;
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return b;
	}
}
